package com.guanmi.ethereum.service.impl;

import com.guanmi.ethereum.configure.EthConfigure;
import com.guanmi.ethereum.constants.GlobalConstants;
import com.guanmi.ethereum.domain.WalletResponseEntity;
import com.guanmi.ethereum.service.EthereumService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.http.HttpService;

import java.io.File;
import java.math.BigInteger;
import java.util.List;

@Service
public class EthereumServiceImpl implements EthereumService {

	private static final Logger log = LoggerFactory.getLogger(EthereumServiceImpl.class);
	
	
	@Autowired
	private EthConfigure  ethConfigure;

	/**
	 * 获取账户列表
	 */
	@Override
	public WalletResponseEntity<List<String>> getAccountlist()  {
		WalletResponseEntity<List<String>> result = new WalletResponseEntity<List<String>>();
		try {
			Web3j web3j = Web3j.build(new HttpService(ethConfigure.getNodeUrl()));
			result.setData(web3j.ethAccounts().send().getAccounts());
			return result;
		} catch (Exception e) {
			log.error("获取账户列表异常:{}", e.getMessage());
			result.setStatus(GlobalConstants.SYSTEM_ERROR);
			return result;
		}

	}

	/**
	 * 创建帐户
	 */
	@Override
	public WalletResponseEntity<Credentials> generateNewWalletFile(String password)  {
		WalletResponseEntity<Credentials> result = new WalletResponseEntity<Credentials>();
		try {
			String fileName = WalletUtils.generateNewWalletFile(password,new File(ethConfigure.getDestinationDirectory()),false);
			Credentials credentials = WalletUtils.loadCredentials(password, ethConfigure.getDestinationDirectory()+File.separator+fileName);
			result.setData(credentials);
			return result;
		} catch (Exception e) {
			log.error("创建帐户异常:{}", e.getMessage());
			result.setStatus(GlobalConstants.SYSTEM_ERROR);
			return result;
		}
	}

	/**
	 * 获取帐户余额
	 */
	@Override
	public WalletResponseEntity<BigInteger> getBalance(String address )  {
		 WalletResponseEntity<BigInteger>  result = new  WalletResponseEntity<BigInteger> ();
		try {
			Admin admin = Admin.build(new HttpService(ethConfigure.getNodeUrl()));
			EthGetBalance ethGetBalance = admin.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();
			result.setData(ethGetBalance.getBalance());
			return result;
		} catch (Exception e) {
			log.error("获取账户余额异常:{}", e.getMessage());
			result.setStatus(GlobalConstants.SYSTEM_ERROR);
			return result;
		}
	}

	/**
	 * 获取用户交易记录数
	 */
	@Override
	public WalletResponseEntity<BigInteger> getTransactionCount(String address )  {
		 WalletResponseEntity<BigInteger>  result = new  WalletResponseEntity<BigInteger> ();
		try {
			Admin admin = Admin.build(new HttpService(ethConfigure.getNodeUrl()));
			EthGetTransactionCount ethGetTransactionCount = admin .ethGetTransactionCount(address, DefaultBlockParameterName.LATEST).sendAsync().get();
			if (null == ethGetTransactionCount) {
				log.error("失获取用户交易记录数败:{}", address);
				result.setStatus(GlobalConstants.PARAM_ERROR);
				return result;
			}
			result.setData(ethGetTransactionCount.getTransactionCount());
			return result;
		} catch (Exception e) {
			log.error("获取用户交易记录数异常:{}", e.getMessage());
			result.setStatus(GlobalConstants.SYSTEM_ERROR);
			return result;
		}
	}

	/**
	 * 获取交易信息
	 */
	@Override
	public WalletResponseEntity<EthTransaction> getTransaction(String transactionHash )  {
		WalletResponseEntity<EthTransaction>  result = new WalletResponseEntity<EthTransaction>();
		try {
			Admin admin = Admin.build(new HttpService(ethConfigure.getNodeUrl()));
			result.setData(admin.ethGetTransactionByHash(transactionHash).sendAsync().get());
			return result;
		} catch (Exception e) {
			log.error("获取交易信息异常:{}", e.getMessage());
			result.setStatus(GlobalConstants.SYSTEM_ERROR);
			return result;
		}
	}

	/**
	 * 获取用户账号
	 */
	@Override
	public WalletResponseEntity<String> getAddress(String walletfile, String password )  {
		WalletResponseEntity<String>  result = new WalletResponseEntity<String>();
		try {
			Credentials credentials = WalletUtils.loadCredentials(password, walletfile);
			result.setData(credentials.getAddress());
			return result;
		} catch (Exception e) {
			log.error("获取用户帐号异常:{}", e.getMessage());
			result.setStatus(GlobalConstants.SYSTEM_ERROR);
			return result;
		}
	}
}
